/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 *
 * Created by hattori <hattori@banana-systems.com>
 *                    <hattori@apache.org> (English Only)
 *
 *
 */


#include "file_util.h"

#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "http_log.h"
#include "ap_config.h"

const char *maos_get_file_content(cmd_parms *parms, char *file, char **content)
{

    apr_file_t *fp;
#if (AP_SERVER_MAJORVERSION_NUMBER == 2 && AP_SERVER_MINORVERSION_NUMBER == 2)
    /* for Apache-2.2 */
    apr_status_t status = apr_file_open(&fp, file, APR_FOPEN_READ, APR_FPROT_UREAD|APR_FPROT_UWRITE, parms->pool);
#elif (defined(AP_SERVER_MAJORVERSION) && defined(AP_SERVER_MINORVERSION))
    apr_status_t status = apr_file_open(&fp, file, APR_READ, APR_UREAD|APR_UWRITE, parms->pool);
#endif

    // content of a public key file
    char *publickey;

    struct stat buf;
    apr_size_t len;

    if (status != APR_SUCCESS ){
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, parms->server, "mod_auth_opensocial : Failed to open file: %s", file); 
        return (char *)apr_pstrcat(parms->pool, "Failed to open file : ", file, NULL);
    }

    stat(file, &buf);
    publickey = (char *)apr_pcalloc(parms->pool, (apr_size_t)buf.st_size+1);
    status = apr_file_read_full(fp, publickey, (apr_size_t)buf.st_size, &len);
    apr_file_close(fp);

    if( status != APR_SUCCESS || (len !=  (apr_size_t)buf.st_size) ){
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, parms->server, "mod_auth_opensocial : Failed to open file: %s , file size and read size didn't match, %d : %d ", file, buf.st_size, len ); 
        return (char *)apr_pstrcat(parms->pool, "Failed to open file : ", file, NULL);
    }

    publickey[len] = '\0';
    *content = publickey;

    return NULL;
}

